<?php
require_once $_SERVER['DOCUMENT_ROOT']."/cms/config/validationDefines.php";
require_once $_SERVER['DOCUMENT_ROOT']."/cms/functions/valid.func.lib.php";
class Form
{
	/**
	 *
	 * @var array
	 */
	var $values;

	/**
	 *
	 * @var str
	 */
	var $errorPrefix;

	/**
	 *
	 * @var array
	 */
	var $fields;

	/**
	 *
	 * @var array
	 */
	var $errors;



	function Form($fields,$values,$extraParams=NULL)
	{
		$this->values = $values;
		$this->fields = $fields;
		$this->extraParams=$extraParams;
		$this->errorPrefix = "";
	}

	function FormValid($extraVldParams=false)
	{
		//[0]-обязательно для заполнения,[1]-минимальная длина,[2]-максимальная длина [3] - уникальное поле 
		$values = array();
		$i=0;
		$this->errors = array();
		//print_r($this->fields);
		foreach ($this->fields as $fieldName=>$validFunction)
		{

			if (is_callable($validFunction['validator']) && !call_user_func_array($validFunction['validator'], array($this->values[$fieldName],$this->extraParams[$fieldName])))
			{

				$this->errors[$i]['field'] = $fieldName;
				$this->errors[$i]['error'] = 'invalid';
				$this->errors[$i]['erroralias']=nonValidField;
				$i++;
			}
			else
			{
				if ($validFunction['lengthParams'][0]==1 && !trim($this->values[$fieldName]))
				{
					$this->errors[$i]['field'] = $fieldName;
					$this->errors[$i]['error'] = 'empty';
					$this->errors[$i]['erroralias']=emptyField;
					$i++;

				}
				elseif(trim($this->values[$fieldName]) || $validFunction['lengthParams'][0])
				{
					if ($validFunction['lengthParams'][1]>0 && strlen($this->values[$fieldName])<$validFunction['lengthParams'][1])
					{
						$this->errors[$i]['field'] = $fieldName;
						$this->errors[$i]['error'] = 'tooshort';
						$this->errors[$i]['erroralias']=tooShortField;
						$i++;
					}
					else
					{
						if ($validFunction['lengthParams'][3]==1 && checkFldUnique($validFunction['fldTable'],$fieldName,$this->values[$fieldName]))
						{
							$this->errors[$i]['field'] = $fieldName;
							$this->errors[$i]['error'] = 'nonUnique';
							$this->errors[$i]['erroralias']=nonUniqueField;
							$i++;
						}
					}
				}
				elseif ($validFunction['lengthParams'][2]>0 && strlen($this->values[$fieldName])>$validFunction['lengthParams'][2])
				{

					$this->errors[$i]['field'] = $fieldName;
					$this->errors[$i]['error'] = 'overflow';
					$this->errors[$i]['erroralias']=overflownField;
					$i++;
				}



				$values[$fieldName] = $this->values[$fieldName];
			}



		}
		//print_R($this->errors);
		if (empty($this->errors))
		{
			$this->values = $values;
			return true;
		}
		else
		{

			return false;
		}
		
	}
}

?>